/*
 * Sapphire
 *
 * Copyright (C) 2018 eq
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111-1301  USA
 *
 */

// not the same as sanitize as of now
const linkifyProtocols = ['http://', 'https://', 'gopher://', 'mailto:'];

// Generate links from plain text (returns node of some kind)
// Technically non-standard - matches most normal links.
// TODO: unit tests
window.linkifyText = function(text) {
    let parens = 0;
    const out = document.createElement('span');
    let currentText = '';
    let i = 0;

    while (i < text.length) {
        if (text[i] === '(') {
            currentText += text[i++];
            parens++;
        }

        for (const protocol of linkifyProtocols) {
            if (text.substr(i, protocol.length) === protocol) {
                if (currentText.length) {
                    out.appendChild(document.createTextNode(currentText));
                }

                currentText = '';

                const m = text.substr(i).match(/(.*?)(\. |, | |$)/);

                const link = document.createElement('a');
                link.setAttribute('href', m[1]);
                link.textContent = m[1];
                out.appendChild(link);

                i += m[1].length;
                break;
            }
        }

        if (i < text.length) {
            currentText += text[i++];
        }
    }

    if (currentText.length) {
        out.appendChild(document.createTextNode(currentText));
    }

    console.log(out);

    return out;
};
